package com.huluobo.a2212mdmdemo.video.page

import android.graphics.drawable.Icon
import android.util.Log
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Send
import androidx.compose.material3.Divider
import androidx.compose.material3.Icon
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.media3.common.MediaItem
import androidx.media3.common.Player.REPEAT_MODE_ONE
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.ui.PlayerView
import coil.compose.AsyncImage
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.huluobo.a2212mdmdemo.R
import com.huluobo.a2212mdmdemo.video.VideoIntent
import com.huluobo.a2212mdmdemo.video.VideoViewModel
import com.huluobo.a2212mdmdemo.video.entity.CommentEntity
import com.huluobo.a2212mdmdemo.video.entity.CommentEntityItem
import com.huluobo.a2212mdmdemo.video.entity.VideoEntityItem
import com.huluobo.lib_base.StateType
import com.huluobo.lib_base.UIState
import com.huluobo.lib_http.Const
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.launch

/**
 *  Created by LC on 2025/6/6.
 */

@Composable
fun VideoPage(vm: VideoViewModel = hiltViewModel()) {
    //compose中获取context
    val context = LocalContext.current
    val videoEntityJson = MMKV.defaultMMKV().decodeString(Const.PARAM_VIDEO_KEY)
    val videoEntityItem = Gson().fromJson(videoEntityJson, VideoEntityItem::class.java)
    var liked by remember {
        mutableStateOf(videoEntityItem.dianzan == 1)
    }

    val commentList = remember {
        SnapshotStateList<CommentEntityItem>()
    }

    var commentString by remember {
        mutableStateOf("")
    }

    //是否弹出评论弹窗
    var isShowComment by remember {
        mutableStateOf(false)
    }

    //视频播放器
    val exoPlayer = remember {
        ExoPlayer.Builder(context).build().apply {
            //设置播放地址
            setMediaItem(MediaItem.fromUri(videoEntityItem.videopath))
            //准备
            prepare()
            //设置准备好直接播放
            playWhenReady = true
            //设置重复次数
            repeatMode = REPEAT_MODE_ONE
        }
//        val player = ExoPlayer.Builder(context).build()
//        player.setMediaSource()
//        player.prepare()
//        player.playWhenReady = true
//        player.repeatMode = REPEAT_MODE_ONE
    }

    LaunchedEffect(key1 = "", block = {
        launch {
            vm.state.collect {
                when (it) {
                    is UIState.OnError -> {
                        ToastUtils.showLong("点赞失败:${it.msg}")
                        Log.e("TagA", "点赞失败:${it.msg}")
                    }

                    UIState.OnLoading -> {}
                    is UIState.OnSuccess<*> -> {
                        if (it.type == StateType.DEFAULT) {
                            ToastUtils.showLong(it.data.toString())
                            liked = true
                        }

                        if (it.type == StateType.COMMENT) {
                            commentList.clear()
                            commentList.addAll(it.data as CommentEntity)
                        }

                        if (it.type == StateType.SEND) {
                            commentList.addAll(0, it.data as CommentEntity)
                        }
                    }
                }
            }
        }
    })

    Column(
        Modifier
            .fillMaxSize()
            .background(Color.Black)
    ) {
        Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.BottomEnd) {
            AndroidView(factory = {
                PlayerView(context).apply {
                    player = exoPlayer
                    //是否使用播放按钮
                    useController = true
                }
            }, modifier = Modifier.fillMaxSize())

            Column(
                Modifier.padding(bottom = 120.dp, end = 20.dp),
                verticalArrangement = Arrangement.spacedBy(5.dp),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Image(
                    painter = painterResource(id = if (liked) R.drawable.liked else R.drawable.like),
                    contentDescription = "",
                    modifier = Modifier
                        .size(40.dp)
                        .clickable {
                            vm.sendIntent(VideoIntent.LikeVideo(videoEntityItem.id))
                        }
                )
                Text(text = "点赞", color = Color.White)

                Image(
                    painter = painterResource(id = R.drawable.baseline_comment_24),
                    contentDescription = "",
                    modifier = Modifier
                        .size(40.dp)
                        .clickable {
                            isShowComment = !isShowComment
                        }
                )
                Text(text = "评论", color = Color.White)
            }

            if (isShowComment) {
                //发起获取评论列表的意图
                vm.sendIntent(VideoIntent.GetComments(videoEntityItem.id))
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .background(Color.White, RoundedCornerShape(topStart = 20.dp, topEnd = 20.dp)),
                    contentAlignment = Alignment.TopEnd
                ) {
                    Image(imageVector = Icons.Default.Close, contentDescription = "", modifier = Modifier
                        .clickable {
                            isShowComment = !isShowComment
                        }
                        .size(40.dp)
                        .padding(end = 10.dp, top = 10.dp))
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(300.dp), contentAlignment = Alignment.BottomCenter
                    ) {
                        //评论列表
                        LazyColumn(content = {
                            items(commentList) {
                                CommentItem(entityItem = it)
                            }
                        }, verticalArrangement = Arrangement.spacedBy(5.dp))
                        OutlinedTextField(
                            value = commentString,
                            onValueChange = { commentString = it },
                            modifier = Modifier
                                .fillMaxWidth()
                                .background(Color.White),
                            trailingIcon = {
                                Icon(
                                    imageVector = Icons.Default.Send,
                                    contentDescription = "",
                                    modifier = Modifier.clickable {
                                        //发送评论
                                        if (!commentString.isNullOrEmpty()) {
                                            val map = mapOf(
                                                Const.PARAM_VIDEO_ID to videoEntityItem.id,
                                                Const.PARAM_MSG to commentString
                                            )

                                            vm.sendIntent(VideoIntent.SendComment(map))
                                        }
                                    })
                            })
                    }
                }
            }
        }
    }

    //当控件被销毁时
    DisposableEffect(Unit) {
        //相当于Activity中的onDestroy
        onDispose {
            //释放当前播放器,方式内存泄漏
            exoPlayer.release()
        }
    }
}

@Composable
fun CommentItem(entityItem: CommentEntityItem) {
    Column(
        Modifier
            .padding(5.dp)
            .fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(5.dp)
    ) {
        Row {
            AsyncImage(
                model = entityItem.icon, contentDescription = "", modifier = Modifier
                    .size(40.dp)
                    .clip(
                        CircleShape
                    ), contentScale = ContentScale.Crop
            )
            Spacer(modifier = Modifier.width(10.dp))
            Text(text = "${entityItem.username}")
        }
        Text(text = "${entityItem.msg}")
        Text(text = "${entityItem.createtime}", fontSize = 12.sp, color = Color.Gray)
        Divider()
    }
}